#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
文件名称: cache_api.py
完整路径: backend/api/cache_api.py
功能说明:
    缓存管理API，提供缓存清理等功能
"""

from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from backend.services.cache_manager import cache_manager

cache_api = Blueprint("cache_api", __name__)


@cache_api.route("/api/cache/cleanup", methods=["POST"])
@jwt_required()
def cleanup_cache():
    """
    清理用户缓存
    用于页面退出时主动清理缓存数据
    """
    try:
        current_user_id = get_jwt_identity()
        cache_key = request.json.get('cache_key') if request.json else None
        
        if cache_key:
            # 清理特定缓存
            if cache_key.startswith(f"agg_data_{current_user_id}_"):
                cache_manager.cleanup_user_cache(current_user_id)
                current_app.logger.info(f"用户{current_user_id}的缓存已清理")
            else:
                current_app.logger.warning(f"用户{current_user_id}尝试清理无权限的缓存")
        else:
            # 清理所有用户缓存
            cache_manager.cleanup_user_cache(current_user_id)
            current_app.logger.info(f"用户{current_user_id}的所有缓存已清理")
        
        return jsonify({"success": True}), 200
        
    except Exception as e:
        current_app.logger.error(f"缓存清理失败: {e}")
        return jsonify({"success": False, "error": str(e)}), 500
